<script setup lang="ts">
  import { CategoryTypeEnum } from '@/shared'
  import type { CategoryEntity } from '@/shared/entity/category'
  import { DoPost, DoPut } from '@/utils/http'
  import { Message } from '@arco-design/web-vue'
  import { isEmpty, pick } from 'lodash-es'
  import { computed, reactive, useTemplateRef, watch } from 'vue'

  interface IProps {
    initialValues?: Partial<CategoryEntity>
    type: CategoryTypeEnum
  }

  const props = defineProps<IProps>()

  const emits = defineEmits<{
    (e: 'refresh'): void
  }>()

  const visible = defineModel({
    type: Boolean || undefined
  })

  const formRef = useTemplateRef('formRef')

  const defaultFormData = {
    name: '',
    sort: 0
  }

  const formData = reactive<Record<string, any>>(structuredClone(defaultFormData))

  const isEdit = computed(() => !isEmpty(props.initialValues))

  const isDish = computed(() => props.type === CategoryTypeEnum.Dish)

  watch(visible, val => {
    if (val) {
      if (isEdit.value) {
        Object.assign(formData, pick(props.initialValues, ['name', 'sort']))
      }
    } else {
      Object.assign(formData, defaultFormData)
    }
  })

  const handlerSubmit = async () => {
    const data = await formRef.value?.validate()
    if (!isEmpty(data)) return false
    if (isEdit.value) {
      await DoPut('/category', {
        ...formData,
        id: props.initialValues?.id,
        type: Number(props.type)
      })
      Message.success('编辑成功')
    } else {
      await DoPost('/category', {
        ...formData,
        type: Number(props.type)
      })
      Message.success('添加成功')
    }
    emits('refresh')
  }
</script>

<template>
  <a-modal
    :title="
      isEdit ? `编辑${isDish ? '菜品分类' : '套餐分类'}` : `添加${isDish ? '菜品分类' : '套餐分类'}`
    "
    title-align="start"
    v-model:visible="visible"
    @before-ok="handlerSubmit"
  >
    <a-form :model="formData" layout="vertical" ref="formRef">
      <a-form-item field="name" label="分类名称" :rules="[{ required: true }]">
        <a-input placeholder="请输入分类名称" v-model="formData.name" />
      </a-form-item>
      <a-form-item field="sort" label="排序" :rules="[{ required: true }]">
        <a-input-number placeholder="请输入排序" v-model="formData.sort" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
